package org.wangblue.document;

import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.wangblue.common.Client;

import java.io.IOException;

/**
 * @Description: 修改文档
 * @Author: WangBlue
 * @Create: 2024-10-22 16:03
 * @Version: 1.0
 **/

public class UpdateDocument {
    private static final String INDEX_NAME = "user";
    private static final String ID = "1001";

    public static void main(String[] args) {
        RestHighLevelClient client = Client.getClient();
        try {
            // 1. 创建 UpdateRequest
            UpdateRequest request = new UpdateRequest(INDEX_NAME, ID);

            // 2. 设置请求体, 对数据进行修改
            request.doc(XContentType.JSON, "sex", "女");

            // 3. 客户端发送请求，获取响应对象
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);

            // 4. 打印响应信息
            System.out.println("_index:" + response.getIndex());
            System.out.println("_id:" + response.getId());
            System.out.println("_result:" + response.getResult());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            System.out.println("文档不存在或更新时发生了其他错误：" + ex.getMessage());
        } finally {
            // 5. 关闭客户端
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
